package com.wh.wisdomsite.xbox.server.controller.pr;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.IService;
import com.wh.wisdomsite.xbox.ba.entity.CommonDict;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.pr.ProjectIn;
import com.wh.wisdomsite.xbox.pr.entity.*;
import com.wh.wisdomsite.xbox.pr.service.*;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.us.entity.User;
import com.wh.wisdomsite.xbox.us.service.IUserService;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import com.wh.wisdomsite.xbox.utils.random.RandomTool;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Constructor;
import java.util.*;

/**
 * 项目Controller
 *
 * @version V1.0
 * @Package: package com.wh.wisdomsite.xbox.server.controller.pr
 * @author: 蔡道行
 * @date: 2018-08-08 10:17
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 **/
@Controller
@RequestMapping(value = "/project")
public class ProjectController {

    private static final Log logger = LogFactory.getLog(ProjectController.class);

    @Autowired
    private IProjectService iProjectService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IUnitService iUnitService;

    @Autowired
    private IUnitSupervisorService iUnitSupervisorService;

    @Autowired
    private IUnitOperatorService iUnitOperatorService;

    @Autowired
    private IUnitInvestigateService iUnitInvestigateService;

    @Autowired
    private  IUnitDesignService iUnitDesignService;

    @Autowired
    private  IUnitCheckService iUnitCheckService;

    @Autowired
    private  IUnitBuildService iUnitBuildService;

    /**
     * 页面跳转
     *
     * @return
     */
    @RequiresPermissions("rules:pr_project_page")
    @RequestMapping(value = "index.do", method = RequestMethod.GET)
    public String index() {
        return "/pr/project/projectList";
    }

    /**
     * 获取项目集合
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:pr_project_find")
    @RequestMapping(value = "/projectList.do")
    public void projectList(HttpServletResponse response, ProjectIn in) {
        try {
            logger.info("加载项目数据列表-->>开始");
            //设置分页
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<Project> page = new Page<Project>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<Project> ewProject = new EntityWrapper<Project>();
//            ewProject.setTableAlias("p");
            ewProject.setEntity(new Project());
            if (StringUtils.isNotEmpty(in.getPrName())) {
                ewProject.like("p.prName", in.getPrName());
            }
            if (StringUtils.isNotEmpty(in.getPrType())) {
                ewProject.eq("p.prType", in.getPrType());
            }
            if (StringUtils.isNotEmpty(in.getPrCode())) {
                ewProject.eq("p.prCode", in.getPrCode());
            }
            if (StringUtils.isNotEmpty(in.getConstructType())) {
                ewProject.like("p.constructType", in.getConstructType());
            }
            if (StringUtils.isNotEmpty(in.getPrPurpose())) {
                ewProject.eq("p.prPurpose", in.getPrPurpose());
            }
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewProject = UserUtils.setEntityWrapper(ewProject, "c1", "o1", "p");
            }
            ewProject.orderBy("createDate", true);
            Page<Map<String,Object>> projectPage = iProjectService.getMapsPage(page,ewProject);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (projectPage.getRecords().size() > 0) {
                for (Map<String,Object> project : projectPage.getRecords()) {
                    JSONObject object = new JSONObject(project);
                    object.put("id", project.get("prId"));
                    if(project.get("prType")!= null){
                        object.put("prType",new JSONObject(project.get("prType")));
                    }
                    if(project.get("prProvice")!=null){
                        object.put("prProvice",new JSONObject(project.get("prProvice")));
                    }
                    if(project.get("prCity")!=null){
                        object.put("prCity",new JSONObject(project.get("prCity")));
                    }
                    if(project.get("prDistrict")!=null){
                        object.put("prDistrict",new JSONObject(project.get("prDistrict")));
                    }
                    if(project.get("prApprovalLevel")!=null){
                        object.put("prApprovalLevel",new JSONObject(project.get("prApprovalLevel")));
                    }
                    if(project.get("constructType")!=null){
                        object.put("constructType",new JSONObject(project.get("constructType")));
                    }
                    if(project.get("prPurpose")!=null){
                        object.put("prPurpose",new JSONObject(project.get("prPurpose")));
                    }
                    if(project.get("bidType")!=null){
                        object.put("bidType",new JSONObject(project.get("bidType")));
                    }
                    if(project.get("company")!=null){
                        object.put("company",new JSONObject(project.get("company")));
                    }
                    if(project.get("office")!=null){
                        object.put("office",new JSONObject(project.get("office")));
                    }
                    array.put(object);
                }
            }
            json.put("total", projectPage.getTotal());
            json.put("rows", array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载项目数据列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("加载项目数据列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 一体化平台获取项目列表
     * @param response
     */
    @RequestMapping(value = "/ythGetProjectList.do")
    public void ythGetProjectList(HttpServletResponse response, @RequestParam(value = "uId") String openUid){
        try{
            EntityWrapper<User> ewUser = new EntityWrapper<>();
            ewUser.setEntity(new User());
            ewUser.eq("openUid", openUid);
            User user = iUserService.selectOne(ewUser);
            if(user == null){
                return;
            }
            EntityWrapper<Project> ewProject = new EntityWrapper<>();
            ewProject.setEntity(new Project());
            List<Project> projectList = iProjectService.selectList(ewProject);

            JSONArray array = new JSONArray();
            if(projectList.size()>0){
                for (Project project : projectList) {
                    //注入每条项目的信息
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("text",project.getPrName());
                    jsonObject.put("id",project.getPrId());
                    array.put(jsonObject);
                }
            }
            ResManager.getTextOut(response).print(array);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 项目详情
     * @param projectIn
     * @param showNewWindow
     * @param request
     * @return
     */
    @RequiresPermissions("rules:pr_project_view")
    @RequestMapping("/projectDesc.do")
    public String projectDesc( ProjectIn projectIn,String showNewWindow, HttpServletRequest request) {
            logger.info("项目详情-->>开始");
            Map<String,Object> project = iProjectService.getMapById(projectIn.getPrId());
            if(project.get("createBy") != null){
                project.put("createBy", UserMapManager.getUserLoginNameInMap(project.get("createBy").toString()));
            }
            if(project.get("updateBy") != null){
                project.put("updateBy", UserMapManager.getUserLoginNameInMap(project.get("updateBy").toString()));
            }
            request.setAttribute("project", project);
            request.setAttribute("showNewWindow", showNewWindow);
            logger.info("项目详情-->>结束");
            return "/pr/project/projectDesc";
    }

    /**
     * 跳转至添加或修改页面
     *
     * @return
     */
    @RequestMapping("/toProject.do")
    public ModelAndView toAddActivity(String prId, HttpServletRequest request) {
        logger.info("添加修改项目跳转-->>开始");
        Map<String,Object> project = null;
        if(StringUtils.isNotEmpty(prId)){
            //project
            project = iProjectService.getMapById(prId);

            request.setAttribute("project", project);

        }
        Integer companyId = UserUtils.getCurrentUser().getCompanyId();
        request.setAttribute("DefaulCompany",companyId);
        Map<String, List<Unit>> unitMapList = iUnitService.getUnitMapList(companyId);
        String prCode = getPrCode();
        request.setAttribute("prCode", prCode);
        request.setAttribute("JCDW", unitMapList.get("JCDW"));
        request.setAttribute("SJDW", unitMapList.get("SJDW"));
        request.setAttribute("JSDW", unitMapList.get("JSDW"));
        request.setAttribute("SGDW", unitMapList.get("SGDW"));
        request.setAttribute("JLDW", unitMapList.get("JLDW"));
        request.setAttribute("KCDW", unitMapList.get("KCDW"));
        logger.info("添加修改项目跳转-->>开始");
        return new ModelAndView("pr/project/projectOption");
    }

    /**
     * 获取一个唯一的项目码
     * @return
     */
    private String getPrCode() {
        String prCode = RandomTool.getNumberLetterSymbol(16);
        EntityWrapper<Project> ewProject = new EntityWrapper<Project>();
        ewProject.setEntity(new Project());
        ewProject.eq("prCode", prCode);
        if(iProjectService.selectCount(ewProject) > 0){
           return getPrCode();
        }
        return prCode;
    }


    /**
     * 更新或者修改
     * @param project
     * @param response
     */
    @RequiresPermissions("rules:pr_project_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(Project project, HttpServletResponse response) {
        try {
            //判断方法是否已经存在,存在即更新.否则为添加
            if (StringUtils.isNotEmpty(project.getPrId())) {
                logger.info("修改项目-->>开始");
                iProjectService.updateById(project);
                logger.info("修改项目-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("项目更新成功"));
            } else {
                logger.info("添加项目-->>开始");
                project.setPrId(UUID.randomUUID().toString().replace("-", ""));
                project.setCreateBy(UserUtils.getCurrentUser().getUsId());
                project.setCreateDate(new Date());
                iProjectService.insert(project);
                logger.info("添加项目-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("项目添加成功"));

            }
            //更新相关表
            if(project.getUnitDesign().getUId()!=null){
                saveRelatedUnit(project, UnitDesign.class, iUnitDesignService);
            }
            if(project.getUnitBuild().getUId()!=null){
                saveRelatedUnit(project, UnitBuild.class, iUnitBuildService);
            }
            if(null != project.getUnitCheck().getUId()){
                saveRelatedUnit(project, UnitCheck.class, iUnitCheckService);
            }
            if(project.getUnitInvestigate().getUId()!=null){
                saveRelatedUnit(project, UnitInvestigate.class, iUnitInvestigateService);
            }
            if(project.getUnitOperator().getUId()!=null){
                saveRelatedUnit(project, UnitOperator.class, iUnitOperatorService);
            }
            if(project.getUnitSupervisor().getUId()!=null){
                saveRelatedUnit(project, UnitSupervisor.class, iUnitSupervisorService);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("操作项目-->>Exception" + e.getMessage());
        }
    }

    /**
     * 给关联单位中间表进行插入和更新公共方法
     * @param pr
     * @param clz
     * @param iService
     * @throws Exception
     */
    private void saveRelatedUnit(Project pr, Class<?> clz, IService iService) throws Exception{
        //设置条件，查询具体的关联unit是否存在
        EntityWrapper<Object> ew = new EntityWrapper<>();
        Constructor con = clz.getConstructor(null);
        ew.setEntity(con.newInstance());
        ew.eq("prId", pr.getPrId());
        //执行查询
        Object obj = iService.getClass().getMethod("selectOne", Wrapper.class)
                .invoke(iService, ew);
        //如果没有查出具体对象，new一个
        if(obj == null){
            obj = con.newInstance();
        }
        //给关联unit,设置项目ID
        obj.getClass().getMethod("setPrId", String.class).invoke(obj,pr.getPrId());
        //得到关联unit的具体名称
        String className = clz.getName().substring(clz.getName().lastIndexOf(".")+1);
        //拼接方法名称
        String methodName = "get" + className;
        //从传入的项目中，获取关联unit实体的入参
        Object unit = pr.getClass().getMethod(methodName).invoke(pr);
        //从unit入参中拿到unitName设置进入关联unit中,等待保存
        methodName = "setUnitName";
        obj.getClass().getMethod(methodName, String.class).invoke(obj,unit.getClass().getMethod("getUnitName").invoke(unit));
        //从unit入参中拿到uId设置进入关联unit中,等待保存
        methodName = "setUId";
        obj.getClass().getMethod(methodName, Integer.class).invoke(obj,unit.getClass().getMethod("getUId").invoke(unit));
        String tempName = unit.getClass().getName();
        String[] split = tempName.split("\\.");
        if("UnitOperator".equals(split[6])){
            methodName = "setUoMgr";
            obj.getClass().getMethod(methodName, String.class).invoke(obj,unit.getClass().getMethod("getUoMgr").invoke(unit));
        }
        //使用传入的具体关联unitService，调用insertOrUpdate进行插入或者更新操作
        iService.getClass().getMethod("insertOrUpdate", Object.class).
               invoke(iService, obj);
    }

    /**
     * 删除项目
     *
     * @param
     * @param response
     */
    @RequiresPermissions("rules:pr_project_del")
    @RequestMapping(value = "/del.do", method = RequestMethod.GET)
    public void del(String prId, HttpServletResponse response) {
        try {
            logger.info("删除项目-->>开始");
            iProjectService.deleteById(prId);
            logger.info("删除项目-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("项目删除成功"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除项目-->>Exception" + e.getMessage());
        }
    }

    /**
     * 通过公司或部门ID查询项目集合
     * @param response
     * @param companyId
     * @param officeId
     */
    @RequestMapping(value = "/projectList.do",method = RequestMethod.GET)
    public void showProjectList(HttpServletResponse response,Integer companyId,Integer officeId){
            List<Project> projectList = new ArrayList<Project>();
            try{
                if(null!=companyId&&companyId!=0){
                    if(null!=officeId&&officeId!=0){
                        projectList = iProjectService.selectProjectListByOfficeId(officeId);
                    }else{
                        projectList = iProjectService.selectProjectListByCompanyId(companyId);
                    }
                }

                JSONArray array = new JSONArray();
                if(projectList.size()>0){
                    for (Project project : projectList) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("id",project.getPrId());
                        jsonObject.put("text",project.getPrName());
                        array.put(jsonObject);
                    }
                }
                ResManager.getTextOut(response).print(array);
            }catch (Exception e){
                e.printStackTrace();
            }
    }

    /**
     * 获取项目集合作为combo使用
     * @param response
     */
    @RequestMapping(value = "/getProjectListForCombo.do", method = RequestMethod.GET)
    public void getProjectListForCombo(HttpServletResponse response,Integer companyId){
        try{
            logger.info("获取项目集合-->>开始");
            Page<Project> page = new Page<Project>();
            page.setCurrent(1);
            page.setSize(10000);
            EntityWrapper<Project> ewProject = new EntityWrapper<Project>();
            ewProject.setEntity(new Project());
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewProject = UserUtils.setEntityWrapper(ewProject, "c1", "o1", "p");
            }
            if(null != companyId){
                ewProject.eq("p.companyId", companyId);
            }
            ewProject.eq("p.dataState", 1);
            ewProject.orderBy("p.createDate", false);
            Page<Map<String,Object>> projectPage = iProjectService.getMapsPage(page,ewProject);
            JSONArray jsonArray = new JSONArray();
            if(projectPage.getRecords().size() > 0){
                for(Map<String,Object> project : projectPage.getRecords()){
                    JSONObject obj = new JSONObject();
                    obj.put("prId",project.get("prId"));
                    obj.put("prName",project.get("prName"));
                    jsonArray.put(obj);
                }
            }
            ResManager.getTextOut(response).print(jsonArray);
            logger.info("获取项目集合-->>结束");
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 获取当前登陆用户所能查看的项目类型数量
     * @param response
     */
    @RequestMapping(value = "/getPrTypeCount.do",method = RequestMethod.GET)
    public void getPrTypeCount(HttpServletResponse response){
        try {
            logger.info("获取项目类型-->>开始");
            Page<Project> page = new Page<Project>();
            page.setCurrent(1);
            page.setSize(Integer.MAX_VALUE);
            EntityWrapper<Project> ewProject = new EntityWrapper<>();
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if (!UserUtils.isSysAdmin()) {
                ewProject = UserUtils.setEntityWrapper(ewProject, "c1", "o1", "p");
            }
            ewProject.orderBy("createDate", true);
            Page<Map<String, Object>> projectPage = iProjectService.getMapsPage(page, ewProject);
            JSONObject json = new JSONObject();
            int house = 0;
            int municipal = 0;
            int total = 0;
            if (projectPage.getRecords().size() > 0) {
                for (int i = 0; i < projectPage.getRecords().size(); i++) {
                    CommonDict prTypeMap = (CommonDict) projectPage.getRecords().get(i).get("prType");
                    String prTypeName = prTypeMap.getPropertyName();
                    String houseType = "房建";
                    String municipalType = "市政";
                    if (prTypeName.equals(houseType)) {
                        house = house + 1;
                    }
                    if(prTypeName.equals(municipalType)){
                        municipal = municipal + 1;
                    }
                }
                total = projectPage.getRecords().size();
            }
            json.put("house", house);
            json.put("municipal",municipal);
            json.put("total", total);
            ResManager.getTextOut(response).print(json);
            logger.info("获取项目类型-->>结束");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
